# coding:utf-8
__author__ = 'zhoushuang'

from base_handler import *
from common_functions import *
import os.path


class mod_execute(BaseHandler):
    """ Execute python or shell script in ./script directory

    Some complexed script could stored in ./script directory, and use mod_execute module to run it.
    Request Parameters:
        module  = mod_execute
        cmdline = ...               # name of script in ./script/
    """

    def __init__(self):
        super(mod_execute, self).__init__()

    def handle(self, reqdict):
        try:
            params = extract_param(reqdict, (('cmdline', 1),))
        except ValueError:
            self.echo.write("#ERROR\tParameter is wrong. reqdict = {} \n".format(reqdict))
            return

        cmdline = params['cmdline']
        # print 'cmdline', cmdline
        scname = cmdline.split()[0]
        if os.path.isfile('script' + os.sep + scname):
            pipe = os.popen('script' + os.sep + cmdline)
            self.echo.write('########## {:^40}##########\n'.format('script' + os.sep + cmdline))
            # self.echo.write('' + os.sep + cmdline + '\n')
            out = pipe.read()
            # print out
            self.echo.write(out)
            ret = pipe.close()
            if ret:
                self.echo.write('#FAILED RETURN CODE:{} \n'.format(ret))
            self.echo.write('########## SUCCESS ##########\n')
            pass
        else:
            self.echo.write('#ERROR\t{} is not exist in script dir\n'.format(scname))
        pass


def gethandler():
    return gethandler.cache


gethandler.cache = mod_execute()

